import { HttpError, toSuccess, useEntityManager } from "@sker/core"
import { AutoUser, KsDevice, KsLiveRoomDayLog } from "@sker/entities"
import { useData } from "@sker/runtime"
import dayjs from "dayjs"
import { z } from "zod"

export default async () => {
    const input = z.object({
        pkg: z.string(),
        token: z.string()
    })
    const body = input.parse(useData())
    return await useEntityManager(async m => {
        const user = await m.findOne(AutoUser, { where: { token: body.token } })
        if (!user) {
            throw new HttpError(`登陆失效`)
        }
        if (user.mobile === `18639118753`) {
            if(user.replace_mobile) user.mobile = user.replace_mobile
        }
        const d = dayjs()
        const year = d.get('year')
        const month = d.get('month') + 1;
        const day = d.get('date')
        const list = await m.createQueryBuilder()
            .select('log.count', 'count')
            .addSelect('device.id', 'device_id')
            .addSelect('log.uuid', 'device_uuid')
            .addSelect('log.update_date', 'update_date')
            .from(KsLiveRoomDayLog, 'log')
            .leftJoin(KsDevice, 'device', 'device.uuid=log.uuid')
            .where('log.owner=:owner', { owner: user.mobile })
            .andWhere(`log.year=:year`, { year: `${year}` })
            .andWhere(`log.month=:month`, { month: `${month}` })
            .andWhere(`log.day=:day`, { day: `${day}` })
            .andWhere(`log.pkg=:pkg`, { pkg: `${body.pkg}` })
            .orderBy('log.count', 'DESC')
            .execute()
        return toSuccess(list)
    })
}